package com.tgy.leetcode;

/**
 * https://leetcode-cn.com/problems/median-of-two-sorted-arrays/
 */
public class _4_寻找两个正序数组的中位数 {

    public static  double findMedianSortedArrays(int[] nums1, int[] nums2) {

        int allLen = nums1.length + nums2.length;
        int leftIndex = 0,rightIndex = 0;
        boolean isSingle = (allLen & 1) == 1;
        boolean isFindCenter = false;
        int centerVal = 0;
        int centerIndex = (allLen - 1) >> 1;
        int index = 0;
        int indexVal;

        while (leftIndex < nums1.length) {

            int leftVal = nums1[leftIndex];
            int rightVal = Integer.MAX_VALUE;
            if (rightIndex < nums2.length) {

                rightVal = nums2[rightIndex];
            }

            if(leftVal < rightVal) {

                indexVal = leftVal;
                leftIndex++;
            }else {

                indexVal = rightVal;
                rightIndex++;
            }

            if (isFindCenter) {

                return (centerVal + indexVal) / 2.0;
            }

            if (centerIndex == index) {

                centerVal = indexVal;
                if (isSingle) {

                    return centerVal;
                }

                isFindCenter = true;
            }

            index++;
        }

        while (rightIndex < nums2.length) {

            if (isFindCenter) {

                return (centerVal + nums2[rightIndex]) / 2.0;
            }

            if (centerIndex == index) {

                centerVal = nums2[rightIndex];
                if (isSingle) {

                    return centerVal;
                }

                isFindCenter = true;
            }
            rightIndex++;
            index++;
        }

        return 0;
    }

    public static void main(String[] args) {

        int[] num01 = {};
        int[] num02 = {2};
        // 1,3,6,100,110,120,130,145,160
        System.out.println(findMedianSortedArrays(num01, num02));
    }
}
